package com.apes.hr.base.service;

import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.hr.base.model.SkillType;
import com.apes.hr.base.repository.SkillTypeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 功能：技能证书类型
 *
 * @author HuJianLin
 * @create 2018-04-28 14:35
 */
@Service("hrSkillTypeService")
public class SkillTypeService extends DomainService {
    @Autowired
    public SkillTypeRepository skillTypeRepository;

    public SkillType save(SimpleRequest request) {
        SkillType skillType = request.getO(SkillType.class);
        return create(skillType);
    }

    public SkillType create(SkillType skillType) {
        return skillTypeRepository.saveAndFlush(skillType);
    }

    public Page<SkillType> findAll(SimpleRequest request) {
        String key = request.get("key");
            // Integer id;
            // try {
            //     id= Integer.valueOf(key);
            // } catch (NumberFormatException e) {
            //     id = -1;
            // }
            return skillTypeRepository.find( key,key,PageRequest.of(request.get("page"), request.get("size")));
    }
    public Page<SkillType> findByAll(SimpleRequest request) {
        List<SkillType> filters = request.get("condition");
        Page<SkillType> skillTypes = skillTypeRepository.findAll(JpaDsl.toCriteria(filters),PageRequest.of(request.get("page"), request.get("size")));
        return skillTypes;
    }

    public Page<SkillType> findByValidIsTrue(SimpleRequest request) {
        List<SkillType> filters = request.get("condition");
        return skillTypeRepository.findByValidIsTrue(PageRequest.of(request.get("page"), request.get("size")));
    }
    public SkillType findOne(String id) {
        return skillTypeRepository.findOne(id);
    }
    public String delete(SimpleRequest request) throws Exception  {
        String id = request.get("id");
        Integer versions = request.get("version");

        SkillType skillType = skillTypeRepository.findOne(id);
        if (skillType == null) throw new RuntimeException("技能证书等级【" + id + "】在系统中不存在。");
        if (skillType.getVersion() != versions) throw new RuntimeException("记录已更新或已删除，请重新提交！");
        skillTypeRepository.delete(skillType);
        return "删除成功";
    }
}
